import json
import re
from flask import Flask, jsonify, request
from flask_cors import CORS
import pymongo
import httpx
from fake_useragent import UserAgent
import redis
from bson.json_util import dumps

app = Flask(__name__)
CORS(app)

# 连接到 Redis
redis_client = redis.StrictRedis(host="redis", port=6379, db=0, decode_responses=True)

# 连接到 MongoDB
mongo_client = pymongo.MongoClient("mongodb://root:Wl728125282@mongo-service:27017/")
db = mongo_client["mbikeyword"]  # MongoDB 数据库
collection = db["keyword"]  # MongoDB 集合

# 搜索 API
@app.route("/api/searchtip", methods=["GET"])
def search():
    key = request.args.get("key")

    if key is None:
        return jsonify(code=0, msg="Invalid search key", data=None), 400
    
    regex = re.compile(key, re.IGNORECASE)  # 使用 IGNORECASE 进行大小写不敏感匹配
    documents = collection.find({"content": regex}).limit(50)
    document_list = []
    for doc in documents:
        # 将 _id 转换为字符串
        doc['_id'] = str(doc['_id'])
        document_list.append(doc)
   
    return jsonify(code=1, msg="success", data=document_list)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
